import 'package:flutter/material.dart';
import 'database_helper.dart';
import 'main.dart';
import 'pwd_card.dart';

class PwdInfoPage extends StatefulWidget {
  final int type; //0 查询，1 新建 ,2 修改
  final Item data;
  const PwdInfoPage({
    Key key,
    this.data,
    this.type,
  }) : super(key: key);

  State<StatefulWidget> createState() => PwdInfoPageState();
}

class PwdInfoPageState extends State<PwdInfoPage> {
  TextEditingController nameController = TextEditingController();
  TextEditingController accountNameController = TextEditingController();
  TextEditingController accountPwdController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController phoneNumController = TextEditingController();
  TextEditingController noteController = TextEditingController();

  bool saveBtn=true;
  bool editBtn=true;
  bool deleteBtn=true;

  bool readOnly=false;

  void initState() {
    super.initState();

    if (widget.type == 0) {
      //查询
      nameController.text = widget.data.name;
      accountNameController.text = widget.data.accountName;
      accountPwdController.text = widget.data.accountPwd;
      emailController.text = widget.data.email;
      phoneNumController.text = widget.data.phoneNum;
      noteController.text = widget.data.note;

      saveBtn=true;
      editBtn=false;
      deleteBtn=false;

      readOnly=true;
    }else if(widget.type==1){
      saveBtn=false;
      editBtn=true;
      deleteBtn=true;

      readOnly=false;
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: widget.type == 0
            ? (readOnly?Text('查询'):Text('修改'))
            :  Text('添加')
      ),
      body: Column(
        children: <Widget>[
          TextField(
            readOnly: readOnly,
            controller: nameController,
            keyboardType: TextInputType.name,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(10.0),
              icon: Icon(Icons.folder),
              labelText: '名称',
            ),
            autofocus: false,
          ),
          TextField(
              readOnly: readOnly,
              controller: accountNameController,
              keyboardType: TextInputType.name,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.account_box),
                labelText: '账号',
              ),
              obscureText: false),
          TextField(
              readOnly: readOnly,
              controller: accountPwdController,
              keyboardType: TextInputType.name,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.lock),
                labelText: '密码',
              ),
              obscureText: false),
          TextField(
              readOnly: readOnly,
              controller: emailController,
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.email),
                labelText: '邮箱',
              ),
              obscureText: false),
          TextField(
              readOnly: readOnly,
              controller: phoneNumController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.phone),
                labelText: '手机',
              ),
              obscureText: false),
          TextField(
              readOnly: readOnly,
              controller: noteController,
              keyboardType: TextInputType.name,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.info),
                labelText: '备注',
              ),
              obscureText: false),
          Expanded(
            child: new Row(
              //crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Offstage(
                  offstage: saveBtn,
                  child: RaisedButton.icon(
                    label:Text('保存'),
                    color: Colors.blue,
                    textColor: Colors.white,
                    icon: Icon(Icons.save),
                    onPressed: () {
                      _insertItem();
                    },
                  ),
                ),
                Offstage(
                  offstage: editBtn,
                  child:  RaisedButton.icon(
                    // heroTag: 'modify',
                    label:readOnly?Text('修改'):Text("保存"),
                    color: Colors.blue,
                    icon: readOnly?Icon(Icons.edit):Icon(Icons.save),
                    textColor: Colors.white,
                    onPressed: () {
                      setState(() {
                        if(readOnly==true) {
                          readOnly=false;
                        }else{
                          _modifyItem(widget.data.id);
                        }
                      });

                    },
                  ),
                ),
                SizedBox(width: 20),
                Offstage(
                  offstage: deleteBtn,
                  child: RaisedButton.icon(
                    //  heroTag: 'delete',
                    label:Text('删除'),
                    color: Colors.blue,
                    icon: Icon(Icons.delete_outline),
                    textColor: Colors.white,
                    onPressed: () {
                      showDialog(context: context,
                          builder: (context) {
                            return AlertDialog(title: Text('警告', style: TextStyle(color: Colors.blueAccent)),
                                content: Text('删除后不可恢复！'),
                                actions: <Widget>[
                                  FlatButton(child: Text("确定"), onPressed: (){
                                    Navigator.of(context).pop();
                                    _deleteItem(widget.data.id);
                                  }),
                                  FlatButton(child: Text("取消"), onPressed: (){
                                    Navigator.of(context).pop();
                                  })
                                ]);
                          });

                    },
                  ),
                ),
              ],
            ),
          ),

        ],
      ),
    );
  }


  void _insertItem() async {
    //插入数据
    Item item = new Item();

    int curCount = await db.getCount();
    print("当前总数 " + curCount.toString());
    item.id = curCount++;
    item.name = nameController.text;
    item.accountName = accountNameController.text;
    item.accountPwd = accountPwdController.text;
    item.email = emailController.text;
    item.phoneNum = phoneNumController.text;
    item.note = noteController.text;

    if (item.name.isNotEmpty && item.accountPwd.isNotEmpty) {
      await db.saveItem(item);

      eventBus.fire(CustomEvent("update_" + item.id.toString()));
      Navigator.pop(context);
    }
  }

  void _deleteItem(int id) async {
    print('删除 ' + id.toString());
    await db.deleteItem(id);
    int count = await db.getCount();
    print('当前总数 ' + count.toString());

    eventBus.fire(CustomEvent("update_" + id.toString()));
    Navigator.pop(context);
  }

  void _modifyItem(int id) async {
    print('修改 ' + widget.data.name);

    Item item = new Item();

    int curCount = await db.getCount();
    print("当前总数 " + curCount.toString());
    item.id = id;
    item.name = nameController.text;
    item.accountName = accountNameController.text;
    item.accountPwd = accountPwdController.text;
    item.email = emailController.text;
    item.phoneNum = phoneNumController.text;
    item.note = noteController.text;

    if (item.name.isNotEmpty && item.accountPwd.isNotEmpty) {
      await db.updateItem(item);

      eventBus.fire(CustomEvent("update_" + item.id.toString()));
      Navigator.pop(context);
    }
  }
}
